<template>
  <view class="clock-in-setting-page">
    <uni-page-header :title="navbarTitle" />
    <view class="main-container">
      <view class="set-reminder-time" @click="onTimeSelect">
        <text class="label">设置每天提醒时间</text>
        <view class="time-value">
          <text class="value">{{ timeValue }}</text>
          <u-icon bold size="15" color="#000" name="arrow-right" />
        </view>
      </view>

      <!-- 选择打卡产品 -->
      <view class="product-select-wrap">
        <view class="title">
          <text>选择打卡产品</text>
          <text>已选：{{ productList.filter(e => e.checked.length !== 0).length }}</text>
        </view>
        <view v-if="productList.length" class="product-list-wrap">
          <view v-for="(item, index) in productList" :key="index" class="product">
            <u-image :src="item.imageUrl" width="80" height="80" radius="10" />
            <view class="info-wrap">
              <view class="info-value">
                <view class="product-name">{{ item.name }}</view>
                <view class="product-desc" v-if="item.detail">{{ item.detail }}</view>
              </view>
            </view>
			<view style="margin-left: auto;">
				<u-checkbox-group v-model="item.checked">
				  <u-checkbox shape="circle" active-color="#78ffe6" icon-placement="right" />
				</u-checkbox-group>
			</view>
          </view>
        </view>
        <u-empty v-else mode="data" icon-size="60" text="暂无可打卡商品" style="padding-bottom: 20px;" />
      </view>

      <view class="action-btn">
        <u-button color="#78ffe6" :text="btnText" @click="onToClockIn" />
      </view>
    </view>

    <u-datetime-picker
      v-model="timeValue"
      :show="datetimePickShow"
      mode="time"
      close-on-click-overlay
      confirm-color="#78ffe6"
      @cancel="onDatetimePickerCancel"
      @confirm="onDatetimePickerConfirm"
    />
  </view>
</template>

<script>
import {
  mapState,
  mapActions
} from 'vuex'
import {
  wx_product_list,
  wx_clockin_rules_start,
  wx_clockin_update
} from '../api/index.js'
import {
  getImg
} from '../utils/index.js'
export default {
  name: 'ClockInSetting',
  options: {
    styleIsolation: 'shared'
  },
  data() {
    return {
      navbarTitle: '开启打卡挑战',
      btnText: '开始打卡',
      datetimePickShow: false,
      timeValue: '08:00',
      productList: [],
      isEnable: null,
      isEditSetting: false
    }
  },
  computed: {
    ...mapState(['clockInRuleData', 'clockInDetail'])
  },
  onLoad(params) {
    this.getProductList()
    console.log('打卡设置页面参数')
    console.log(params)
    this.isEditSetting = false
    // 打卡页面跳转过来修改打卡设置
    if (params.action) {
      this.isEditSetting = true
      this.navbarTitle = '修改打卡设置'
      this.btnText = '确认调整'
    }
  },
  methods: {
    ...mapActions(['getClockInRuleData']),
    async getProductList() {
      const data = await wx_product_list()
      this.productList = data.product_list.map(e => {
        e.checked = []
        e.imageUrl = getImg(e.image)
        return e
      })

      // 修改打卡配置并且本地打卡详情有值
      if (this.isEditSetting && this.clockInDetail.clockin_data) {
        const {
          notify_time,
          product_ids
        } = this.clockInDetail.clockin_data
        this.timeValue = notify_time
        const ids = product_ids.split(',').map(e => +e)
        this.productList.forEach(e => {
          const idx = ids.find(id => id === e.id)
          e.checked = idx > -1 ? [''] : []
        })
      }
    },

    onTimeSelect() {
      this.datetimePickShow = true
    },

    onDatetimePickerCancel() {
      this.datetimePickShow = false
    },

    onDatetimePickerConfirm() {
      this.datetimePickShow = false
    },

    // 开始打卡 / 确认调整
    async onToClockIn() {
      const _this = this
      const ids = this.productList.filter(e => e.checked.length !== 0).map(e => e.id)
      // if (ids.length === 0) {
      //   this.$utils.showToast('请选择打卡商品')
      //   return
      // }
      let params = {
        notify_time: this.timeValue,
        product_ids: ids.join(',')
      }
      if (this.isEditSetting) {
        // 修改打卡设置
        Object.assign(params, {
          ruleid: this.clockInRuleData.id
        })
        console.log('需要修改的打卡设置数据')
        console.log(params)
        await wx_clockin_update(params)
        this.$utils.showToast('修改成功')
      } else {
        // 如果打卡关闭，重新打卡后需要传is_enable
        if (this.clockInRuleData.is_enable === false) {
          Object.assign(params, {
            is_enable: true
          })
        }
        console.log('需要添加的打卡设置数据')
        console.log(params)
        await wx_clockin_rules_start(params)
      }

      // 参加打卡或者修改打卡配置后更新本地打卡规则数据，主要获取最新打卡状态
      this.getClockInRuleData()
      uni.$emit('clockin-setting-update', {
        data: 'update'
      })
      this.$utils.switchTabToPage('/pages/clockIn')
    }
  }
}
</script>

<style lang="scss" scoped>
	.clock-in-setting-page {
		font-size: 30rpx;

		.main-container {
			.set-reminder-time {
				width: 85%;
				padding: 20rpx;
				margin: 30rpx auto;
				@include flex-between;
				border-radius: 50rpx;
				background-color: #FFF;
				font-weight: bolder;

				.time-value {
					@include flex-column-center;
				}
			}

			.product-select-wrap {
				width: 95%;
				padding: 20rpx;
				margin: 40rpx auto;
				border-radius: 15rpx;
				background-color: #FFF;

				.title {
					font-weight: bolder;
					padding-bottom: 20rpx;
					@include flex-between;
				}

				.product-list-wrap {

					// margin-bottom: 200rpx;
					.product {
						padding: 20rpx;
						padding-right: 0;
						@include flex-column-center;
						gap: 15rpx;
						border-top: 1px solid #E6E6E6;

						.info-wrap {
							@include flex-center;
							gap: 20rpx;

							.info-value {
								flex: 1;

								.product-name {
									font-weight: 600;
									font-size: 28rpx;
									margin-bottom: 28rpx;
									@include text-ellipsis;
								}

								.product-desc {
									font-size: 24rpx;
									color: rgba(0, 0, 0, 0.5);
									@include text-ellipsis(2);
								}
							}
						}
					}
				}
			}
		}
	}

	::v-deep.action-btn {
		width: 100%;
		height: 200rpx;
		position: fixed;
		left: 0;
		bottom: 0;
		@include flex-center;
		background-color: #F5F5F5;

		button {
			width: 60%;
			color: #000 !important;
			font-weight: bolder;
		}
	}
</style>
